package com.jbh.fourclibrary.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jbh.fourclibrary.R;
import com.jbh.fourclibrary.util.Util;


public class ActionBarView extends LinearLayout {

    /**标题*/
    private String strTitle;
    /**标题的颜色*/
    private int titleColor = Color.BLACK;
    /**是否支持返回按钮*/
    private boolean isBackEnable = true ;
    /**是否显示默认右边按钮*/
    private boolean isDefaultRightViewEnable = false ;
    /**设置默认右边按钮文本信息*/
    private String defaultRightViewText;
    /**默认右边文本字体颜色*/
    private int defaultRightViewTextColor = getResources().getColor(R.color.black);
    /**默认右边文本字体大学*/
    private int defaultRightViewTextSize = 16;
    /**返回按钮图标*/
    private int backIcon = R.mipmap.back;
    /**返回按钮图标颜色*/
    private int backIconColor = R.color.black;
    /**view的背景色*/
    private int startColor = getResources().getColor(R.color.defaultThemeColor) ;
    /**view的背景色*/
    private int endColor =  getResources().getColor(R.color.defaultThemeColor0);
    /**view默认高度*/
    private int actionHeight = dpToPx(50) ;
    /**是否支持输入  默认不支持*/
    private boolean isSupportEditView = false;


    public ActionBarView(Context context) {
        this(context,null);
    }

    public ActionBarView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ActionBarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(HORIZONTAL);
        setGravity(Gravity.BOTTOM);
        initAttr(context, attrs, defStyleAttr);
        init(Util.getAppCompatActivity(getContext()));
    }



    /**
     * 属性
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    @SuppressLint("ResourceType")
    private void initAttr(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ActionBarView, 0, defStyleAttr);
        int count = array.getIndexCount();
        for (int i=0;i<count;i++){
            int attr = array.getIndex(i);
            if (attr == R.styleable.ActionBarView_strTitle) {
                strTitle = array.getString(attr);
            } else if (attr == R.styleable.ActionBarView_titleColor) {
                titleColor = array.getColor(attr, Color.BLACK);
                /*默认显示*/
            } else if (attr == R.styleable.ActionBarView_isBackEnable) {
                isBackEnable = array.getBoolean(attr, true);
            } else if (attr == R.styleable.ActionBarView_isDefaultRightViewEnable) {
                isDefaultRightViewEnable = array.getBoolean(attr, false);
            } else if (attr == R.styleable.ActionBarView_defaultRightViewText) {
                defaultRightViewText = array.getString(attr);
            } else if (attr == R.styleable.ActionBarView_defaultRightViewTextColor) {
                defaultRightViewTextColor = array.getColor(attr, 0);
            } else if (attr == R.styleable.ActionBarView_defaultRightViewTextSize) {
                defaultRightViewTextSize = array.getInt(attr, 16);
            } else if (attr == R.styleable.ActionBarView_backIcon) {
                backIcon = array.getResourceId(attr, 0);
            } else if (attr == R.styleable.ActionBarView_startColor) {
                startColor = array.getColor(attr, 0);
            } else if (attr == R.styleable.ActionBarView_endColor) {
                endColor = array.getColor(attr, 0);
            } else if (attr == R.styleable.ActionBarView_actionHeight) {
                actionHeight = dpToPx(array.getInt(attr, 0));
            } else if (attr == R.styleable.ActionBarView_backIconColor) {
                backIconColor = array.getResourceId(attr, 0);
            } else if (attr == R.styleable.ActionBarView_isSupportEditView) {
                isSupportEditView = array.getBoolean(attr, false);
            } else if (attr == R.styleable.ActionBarView_editTextHint) {
                editTextHint = array.getString(attr);
            } else if (attr == R.styleable.ActionBarView_isSupportInput) {
                isSupportInput = array.getBoolean(attr, false);
            } else if (attr == R.styleable.ActionBarView_isClickBack) {
                isClickBack = array.getBoolean(attr, false);
            } else if (attr == R.styleable.ActionBarView_ImInputLeftIcon) {
                ImInputLeftIcon = array.getResourceId(attr, 0);
            }
        }


        array.recycle();
        /*初始化view*/
        initView(context);
        /*初始化配置*/
        initData();
    }



    /**
     */
    private void initData() {
        back.setVisibility(isBackEnable?View.VISIBLE:View.GONE);
        setTitle(strTitle);
        setTitleColor(titleColor);
        setBackIcon(backIcon);
        setBackIconColor(backIconColor);
        setBackground(startColor,endColor);
        /*选中主题*/
//        ThemeUtil.instance().changeViewTheme(this, ThemeUtil.ViewType.BAR,0);
    }


    public TextView getTitle() {
        return title;
    }


    public void setTitleTextSize(int size) {
        title.setTextSize(size);
    }



    /**
     *
     * @param startColor
     */
    public void setBackground(int startColor){
        setBackgroundResource(startColor);
    }




    /**
     *
     * @param startColor
     */
    public void setBackground(int startColor, int endColor){
        GradientDrawable gradientDrawable=new GradientDrawable();
        gradientDrawable.setColors(new int[]{startColor, endColor});
        setBackground(gradientDrawable);
    }


    /**
     * 设置返回按钮背景图
     * @param backIcon
     */
    private void setBackIcon(int backIcon) {
        if (back!=null)
        back.setImageResource(backIcon);
    }



    /**
     * 设置标题颜色
     * @param titleColor
     */
    public void setTitleColor(int titleColor) {
        if (title!=null)
            title.setTextColor(titleColor);
    }



    /**
     * 设置返回按钮背景色
     * @param color
     *
     */
    public void setBackIconColor(@ColorRes int color){
       back.setImageDrawable(GetTintDrawable(backIcon,color));
    }



    /**
     * 默认的右边按钮
     */
    private TextView defaultRightView ;
    private void defaultRightView() {
        if (isDefaultRightViewEnable){
            defaultRightView = new TextView(getContext());
            defaultRightView.setGravity(Gravity.CENTER);
            defaultRightView.setTextSize(18);
            defaultRightView.setPadding(dpToPx(10),0,dpToPx(10),0);
            LayoutParams layoutParams=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
            linearLayout.addView(defaultRightView,layoutParams);

            defaultRightView.setTextColor(defaultRightViewTextColor);
            defaultRightView.setText(defaultRightViewText);
            defaultRightView.setTextSize(defaultRightViewTextSize);
        }
    }


    public TextView getDefaultRightView() {
        return defaultRightView;
    }



    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        ViewGroup.LayoutParams param = getLayoutParams();
        param.height = Build.VERSION.SDK_INT >=19 ? (actionHeight+getStatusBarHeight(getContext())): actionHeight;
        param.width = getResources().getDisplayMetrics().widthPixels ;
        setLayoutParams(param);
    }



    /**
     * 初始化 view
     *
     * @param context
     */
    private RelativeLayout rootView ;
    private void initView(Context context) {
        rootView=new RelativeLayout(context);
        rootView.setGravity(Gravity.CENTER_VERTICAL);
        LayoutParams rootParams = new LayoutParams(LayoutParams.MATCH_PARENT,actionHeight);
        addView(rootView,rootParams);
        addLeftView(context);
        addRightView(context);
        if (!isSupportEditView){
            addTitleView(context);
        }else {
            addEditView(context);
        }
        defaultRightView();
    }


    /***/
    public TextView editText ;
    /**默认提示语*/
    private String editTextHint = "请输入关键字";
    /**输入框的view*/
    private LinearLayout layEditView;
    /**输入文字颜色*/
    private int editTextColor = getResources().getColor(R.color.black);
    private ImageView imSearch;
    private boolean isSupportInput = false;
    private EditText editTextInput;

    private int ImInputLeftIcon = 0 ;
    /**/
    private ImageView im_left;



    /**
     *
     * @param onClickListener
     */
    public void setImLeftListener(OnClickListener onClickListener){
        if (im_left!=null)
            im_left.setOnClickListener(onClickListener);
    }


    /**
     * 設置搜索内容
     *
     * @param text
     */
    public void setEditTextInput(String text){
        if (editTextInput!=null){
            editTextInput.setText(text);
            if (!TextUtils.isEmpty(text)){
                editTextInput.setSelection(text.length());
            }
        }
    }


    /**
     * 支持输入框
     * @param context
     */
    private void addEditView(Context context) {
        layEditView = new LinearLayout(getContext()) ;
        layEditView.setGravity(Gravity.CENTER_VERTICAL);
        RelativeLayout.LayoutParams inputView=new
                RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT ,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        inputView.addRule(RelativeLayout.CENTER_IN_PARENT);
        rootView.addView(layEditView,inputView);

        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setColor(getResources().getColor(R.color.pageColor));
        gradientDrawable.setCornerRadii(new float[]{
                dpToPx(25),dpToPx(25),
                dpToPx(25),dpToPx(25),
                dpToPx(25),dpToPx(25),
                dpToPx(25),dpToPx(25)});
        layEditView.setBackground(gradientDrawable);

        MarginLayoutParams marginLayoutParams = (MarginLayoutParams) layEditView.getLayoutParams();
        marginLayoutParams.leftMargin = dpToPx(60);
        marginLayoutParams.rightMargin = dpToPx(60);
        marginLayoutParams.height = dpToPx(35);


        if (ImInputLeftIcon != 0){
            im_left = new ImageView(getContext());
            im_left.setImageResource(ImInputLeftIcon);
            im_left.setPadding(20,0,0,0);
            LayoutParams layoutParams = new LayoutParams(dpToPx(30),ViewGroup.LayoutParams.MATCH_PARENT);
            layEditView.addView(im_left,layoutParams);
        }


        if (isSupportInput){
            editTextInput=new EditText(context);
            editTextInput.setPadding(dpToPx(10),0,dpToPx(10),0);
            editTextInput.setSingleLine(true);
            editTextInput.setHint(editTextHint);
            editTextInput.setGravity(Gravity.CENTER_VERTICAL);
            editTextInput.setBackground(null);
            editTextInput.setTextSize(14);
            editTextInput.setTextColor(editTextColor);
            editTextInput.setGravity(Gravity.CENTER_VERTICAL);
            editTextInput.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
            editTextInput.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    if (onAddTextInputListener==null)return;
                    onAddTextInputListener.onChangeInputText(editTextInput.getText().toString().trim().toString());
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            });
            // getTextView01设置权重是1
            LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,1);
            layEditView.addView(editTextInput,lp);

            editTextInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH){
                        String searchKey = editTextInput.getText().toString().trim() ;
                        if (!TextUtils.isEmpty(searchKey)){
                            if (onAddTextInputListener!=null){
                                onAddTextInputListener.onClickChangeInput(searchKey+"");
                            }
                        }
                        return true;
                    }
                    return false;
                }
            });
        }else {
            editText=new TextView(context);
            editText.setPadding(dpToPx(10),0,dpToPx(10),0);
            editText.setSingleLine(true);
            editText.setHint(editTextHint);
            editText.setGravity(Gravity.CENTER_VERTICAL);
            editText.setBackground(null);
            editText.setTextSize(14);
            editText.setTextColor(editTextColor);
            editText.setGravity(Gravity.CENTER_VERTICAL);
            // getTextView01设置权重是1
            LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,1);
            layEditView.addView(editText,lp);
        }
        imSearch=new ImageView(getContext());
        imSearch.setMinimumWidth(dpToPx(50));
        imSearch.setImageResource(R.mipmap.search_2);
        layEditView.addView(imSearch);
    }


    /**
     * 搜索按钮
     * @param onClickSearchListener
     */
    public void setOnClickSearchListener(OnClickListener onClickSearchListener) {
        if (imSearch!=null)
            imSearch.setOnClickListener(onClickSearchListener);
    }




   private OnAddTextInputListener onAddTextInputListener;
    public void addTextInputListener(OnAddTextInputListener onAddTextInputListener){
        this.onAddTextInputListener=onAddTextInputListener;
    }





    public interface OnAddTextInputListener{
        void onChangeInputText(String text);
        void onClickChangeInput(String text);
    }





    /**
     * 搜索按钮
     *
     * @param onClickListener
     */
    public void setOnSearchListener(OnClickListener onClickListener){
        if (editText!=null){
            editText.setOnClickListener(onClickListener);
            imSearch.setOnClickListener(onClickListener);
        }
    }





    /**
     * 扩展 view
     * @param context
     */
    private LinearLayout linearLayout;
    private void addRightView(Context context) {
        linearLayout=new LinearLayout(context);
        linearLayout.setOrientation(HORIZONTAL);
        linearLayout.setGravity(Gravity.CENTER_VERTICAL);
        RelativeLayout.LayoutParams commonP=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT , RelativeLayout.LayoutParams.MATCH_PARENT);
        commonP.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        rootView.addView(linearLayout,commonP);
    }





    /**
     * @param view
     */
    public void addRight(View view){
        linearLayout.addView(view);
    }

    /**
     * @param view
     */
    public void addRight(View view,LayoutParams params){
        linearLayout.addView(view,params);
    }


    /**
     * 标题按钮
     *
     * @param context
     */
    private TextView title ;
    private LinearLayout titleContentView;
    private void addTitleView(Context context) {
        titleContentView = new LinearLayout(context);
        titleContentView.setGravity(Gravity.CENTER);
        title=new TextView(context);
        title.setTextColor(Color.WHITE);
        title.setText("title");
        title.setGravity(Gravity.CENTER);
        title.setTextSize(18);
        titleContentView.addView(title);
        RelativeLayout.LayoutParams titleP=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT , RelativeLayout.LayoutParams.MATCH_PARENT);
        titleP.addRule(RelativeLayout.CENTER_IN_PARENT);
        rootView.addView(titleContentView,titleP);
    }



    /**
     * 扩展标题
     *
     * @param view
     */
    public void addTitleView(View view){
        if (titleContentView!=null){
            titleContentView.removeAllViews();
            titleContentView.addView(view);
        }
    }




    /**
     * 设置标题
     *
     * @param str
     */
    public void setTitle(String str) {
        if (title!=null)
        title.setText(str);
    }




    /**
     * 左边的返回按钮
     *
     * @param context
     */
    public ImageView back ;

    /**支持直接点击*/
    boolean isClickBack = false;
    private void addLeftView(Context context) {
        back=new ImageView(context);
        back.setImageResource(R.mipmap.back);
        back.setPadding(0,dpToPx(15),0,dpToPx(15));
        RelativeLayout.LayoutParams backP=new RelativeLayout.LayoutParams(dpToPx(50),dpToPx(50));
        backP.addRule(RelativeLayout.ALIGN_PARENT_LEFT | RelativeLayout.CENTER_VERTICAL);
        rootView.addView(back,backP);


        if (isClickBack){
            back.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Util.getAppCompatActivity(getContext()).finish();
                }
            });
        }
    }



    /**
     * @param dp
     * @return
     */
    private int dpToPx(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }


    /**
     * 初始化
     *
     * @param activity
     */
    private void init(Activity activity){
        if (Build.VERSION.SDK_INT>=19){
            if (Build.VERSION.SDK_INT >= 21) {
                View decorView =activity. getWindow().getDecorView();
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                decorView.setSystemUiVisibility(option);
                activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
            }else {
                //透明状态栏
                activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                //透明导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
            /*内距顶部*/
            setPadding(0,getStatusBarHeight(activity),0,0);
        }
    }





    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        if (Build.VERSION.SDK_INT>=19) {
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = context.getResources().getDimensionPixelSize(resourceId);
            }
            return result;
        }
        return result;
    }




    /**
     *  设置着色图片
     * @param resourceId 图片资源id
     * @param color 颜色资源 id
     * @return 图片
     */
    public  Drawable GetTintDrawable(int resourceId, int color) {
        Drawable originalDrawable = ContextCompat.getDrawable(getContext(), resourceId);
        assert originalDrawable != null;
        Drawable tintDrawable = DrawableCompat.wrap(originalDrawable).mutate();
        DrawableCompat.setTintList(tintDrawable, ContextCompat.getColorStateList(getContext(), color));
        return tintDrawable;
    }

}



